package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.emmp_ard.scancapture.ScanCaptureActivity;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.ArrangeTaskPauseDTO;
import com.huaxin.common.Entity.ArrangeWorkTask;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.HxInHousePollingBean;
import com.huaxin.common.Entity.WorkTask;
import com.huaxin.common.Entity.WorkTaskListDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.BottomSheetDialog;
import com.huaxin.common.view.pulltorefresh.CustomHeaderLayout;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.dialog.HxSPTFinishWorkDialog;
import com.huaxin.hxcloud.dialog.TaskFeeDialog;
import com.huaxindata.common.util.HxLogUtils;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/28.
 */
public class WorkTaskListActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2 {

    public static final int WORK_TASK_STATE_NOT_START = 0x00;
    public static final int WORK_TASK_STATE_START     = 0x01;
    public static final int WORK_TASK_STATE_END       = 0x02;


    RecyclerView mWorkTaskList;
    ArrayList<WorkTask> workTaskDatas = new ArrayList<>();
    WorkTaskListAdapter workTaskListAdapter;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.tv_number)
    TextView                  tvNumber;
    @BindView(R.id.tv_worker)
    TextView                  tvWorker;
    @BindView(R.id.tv_car)
    TextView                  tvCar;
    @BindView(R.id.bt_change)
    Button                    btChange;
    @BindView(R.id.tv_station_name)
    TextView                  mTvStationName;
    @BindView(R.id.bt_start)
    ImageButton               btStart;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    @BindView(R.id.content)
    FrameLayout               content;
    @BindView(R.id.fl_act)
    FrameLayout               fl_act;
    @BindView(R.id.tv_stop_task)
    ImageView                 tv_stop_task;
    @BindView(R.id.tv_work_route)
    TextView                  tv_work_route;

    private ArrangeWorkTask arrangeTask;

    private int                                 ret_pos       = 0;
    private List<HxInHousePollingBean.DataBean> mDataBeanList = new ArrayList<>();
    HxInHousePollingAdpater mPollingAdpater;

    /*任务结束弹窗*/
    private TaskFeeDialog taskFeeDialog;
    // private String[] mSelectArray = {"结束任务", "结束任务并还车", "取消"};

    public static void start(Activity context, ArrangeWorkTask data) {
        Intent intent = new Intent(context, WorkTaskListActivity
                .class);
        intent.putExtra(Constants.IK_ARRANGE_WT, data);
        context.startActivityForResult(intent, Constants.RET_AT_STATE);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_ARRANGE_WT)) {
            arrangeTask = extras.getParcelable(Constants.IK_ARRANGE_WT);
        } else {
            finish();
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_worktask_list;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void requestData() {
        /* TaskType 0 厂站巡检 1其他派工 2 厂内巡检
        taskType = 1  排泥；
        taskType = 2  维修；
        taskType = 5  保养(养护)
        taskType = 6  加药*/
        switch (arrangeTask.getTaskType()) {
            case 2:
                //隐藏车辆和更换按钮
                tvCar.setVisibility(View.GONE);
                btChange.setVisibility(View.GONE);
                //loadText("站点：", mTvStationName, arrangeTask.getOrgName());
                ApiRequestDatafindXunJianStructure(LOADING, null);
                break;
            case 6:
                break;
            default:
                ApiRequestData(LOADING, null);
                break;

        }
        mTvStationName.setVisibility(View.GONE);

    }


    @Override
    public void initView() {

        setSupportActionBar(toolbar);
        toolbar.setTitle("任务单");

        pullView.setHeaderLayout(new CustomHeaderLayout(this));
        pullView.setOnRefreshListener(this);
        mWorkTaskList = pullView.getRefreshableView();

        mWorkTaskList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));

        mWorkTaskList.setHasFixedSize(true);
        if (arrangeTask.getTaskType() == 2) {
            mPollingAdpater = new HxInHousePollingAdpater(this, mDataBeanList);
            mWorkTaskList.setAdapter(mPollingAdpater);
        } else {
            workTaskListAdapter = new WorkTaskListAdapter();
            mWorkTaskList.setAdapter(workTaskListAdapter);
            setOnItemClickListener();
        }

        if (arrangeTask.getIsSuspended() == 0) {
            tv_stop_task.setImageResource(R.drawable.control_pause);
        } else if (arrangeTask.getIsSuspended() == 1) {
            tv_stop_task.setImageResource(R.drawable.control_play);
        }
        //工单暂停只存在于spt
        Log.e("lwjing", "UserManager.getOrgCode()=" + UserManager.getFirstOrgCode());
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            tv_stop_task.setVisibility(View.VISIBLE);
            tv_work_route.setVisibility(View.VISIBLE);
        } else {
            tv_stop_task.setVisibility(View.GONE);
            tv_work_route.setVisibility(View.GONE);
        }
        updateView();

    }

    /**
     * 条目点击事件
     */
    private void setOnItemClickListener() {
        workTaskListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                if (arrangeTask.getState() == WORK_TASK_STATE_NOT_START) {
                    ToastUtil.showToast("请先开启任务");
                    return;
                }
                WorkTask data = workTaskDatas.get(position);
                ret_pos = position;
                if (data.getTaskType() == 0) {
                    CheckTaskDetailActivity.start(WorkTaskListActivity.this, data, arrangeTask.getState());
                } else {
                    RepairTaskDetailActivity.start(WorkTaskListActivity.this, data);
                }
            }
        });
    }

    protected void updateView() {
        if (mPollingAdpater != null) {
            mPollingAdpater.setState(arrangeTask.getState());
        }
        loadText("单号：", tvNumber, arrangeTask.getArrangeTaskCode());
        loadText("负责人：", tvWorker, StringUtils.toString(arrangeTask
                .getWorkers()));
        switch (arrangeTask.getState()) {
            case WORK_TASK_STATE_NOT_START:
                btChange.setVisibility(View.VISIBLE);
                btStart.setImageResource(R.drawable.icon_start_task);
                loadText("车辆：", tvCar, arrangeTask.getPlanVehicle(), "未绑定车辆");
                break;
            case WORK_TASK_STATE_START:
                btChange.setVisibility(View.GONE);
                btStart.setImageResource(R.drawable.icon_finish_task);
                loadText("车辆：", tvCar, arrangeTask.getRealVehicle(), "未绑定车辆");
                break;
            case WORK_TASK_STATE_END:
                btChange.setVisibility(View.GONE);
                btStart.setImageResource(R.drawable.icon_finish);
                tv_stop_task.setVisibility(View.GONE);
                loadText("车辆：", tvCar, arrangeTask.getRealVehicle(), "未绑定车辆");
                break;
        }
        //TaskType 0 厂站巡检 1其他派工 2 厂内巡检

        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode()) || arrangeTask.getTaskType() == 2) {
            tvCar.setVisibility(View.GONE);
            btChange.setVisibility(View.GONE);
        } else {
            tvCar.setVisibility(View.INVISIBLE);
            btChange.setVisibility(View.INVISIBLE);
        }
    }


    private void ApiAcceptArrangeTask() {
        final Dialog dialog = DialogUtil.getWaitDialog(this, "开启任务...");
        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().acceptArrangeTask(arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        arrangeTask.setState(WORK_TASK_STATE_START);
                        arrangeTask.setRealVehicle(arrangeTask.getPlanVehicle());
                        updateView();
                        setResult();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据错误");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }

    private void ApiCloseArrangeTask(final int position, final String fee) {
        final Dialog dialog = DialogUtil.getWaitDialog(this, "完成任务...");
        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().closeArrangeTask(arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        //关闭弹框
                        if (taskFeeDialog != null && taskFeeDialog.isShowing()) {
                            taskFeeDialog.dismiss();
                            arrangeTask.setState(WORK_TASK_STATE_END);
                            // updateView();
                            setResult();
                            finish();
                            //上传费用
                            if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
                                apiUploadArrangeTaskCost(fee);
                            }
                            //还车
                            if (position != 0) {
                                ApiUnbindVehicle();
                            }
                        } else {
                            if (baseDTO != null) {
                                ToastUtil.showToast(baseDTO.getMsg());
                            } else {
                                ToastUtil.showToast("数据异常");
                            }
                        }
                    } else {
                        ToastUtil.showToast("数据错误");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }

    /**
     * 上传费用
     *
     * @param fee
     */

    private void apiUploadArrangeTaskCost(String fee) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().uploadArrangeTaskCost(arrangeTask.getId(), fee);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                ToastUtil.showToast(baseDTO.getMsg());
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                HxLogUtils.d("-onFailure--上传费用---" + t);
                ToastUtil.showToast("费用上传失败");
            }
        });
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        if (arrangeTask.getTaskType() == 2) {
            ApiRequestDatafindXunJianStructure(LOAD_SUCCESS, refreshView);
        } else {
            ApiRequestData(LOAD_SUCCESS, refreshView);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        refreshView.onRefreshComplete();
    }

    protected class WorkTaskListAdapter extends BaseQuickAdapter<WorkTask, BaseViewHolder> {


        /**
         * 构造方法，传入item的布局
         */
        public WorkTaskListAdapter() {
            super(R.layout.item_worktask);
        }


        /**
         * item界面更新
         *
         * @param baseViewHolder
         * @param workTask
         */
        @Override
        protected void convert(BaseViewHolder baseViewHolder, WorkTask workTask) {
            TextView title = baseViewHolder.getView(R.id.title);
            TextView station = baseViewHolder.getView(R.id.station);
            TextView address = baseViewHolder.getView(R.id.address);
            TextView endDate = baseViewHolder.getView(R.id.endDate);
            TextView state = baseViewHolder.getView(R.id.state);
            TextView typeTv = baseViewHolder.getView(R.id.type_tv);
            loadText(title, workTask.getTitle(), "工单未填标题");
            loadText("站点：", station, workTask.getStationName() + "(" + workTask
                    .getStationCode() +
                    ")");
            loadText("所属地址：", address, workTask.getStationAddr());
            if (workTask.getFinishDate() == null) {
                loadText("截止时间：", endDate, dateFormat(workTask.getRequireDate()), "工单未填截止时间");
            } else {
                loadText("完成时间：", endDate, dateFormat(workTask.getFinishDate()), "无");
            }
            //站点巡检单状态:0、未派工;1、已派工;2、处理中; 3已完成
            switch (workTask.getWorkTaskState()) {
                case 0:
                    loadText(state, "未派工");
                    break;
                case 1:
                    loadText(state, "未开始");
                    break;
                case 2:
                    loadText(state, "进行中");
                    break;
                case 3:
                    loadText(state, "已完成");
                    break;
                default:
                    break;
            }
            String falgType;
            switch (workTask.getTaskType()) {
                //巡检单
                case 0:
                    falgType = "巡";
                    break;
                case 1:
                    //排泥单
                    falgType = "排";
                    break;
                case 2:
                    //维修单
                    falgType = "修";
                    break;
                case 5:
                    //保养单
                    falgType = "养";
                    break;
                case 6:
                    //加药单
                    falgType = "药";
                    break;
                default:
                    falgType = "修";
                    break;
            }
            typeTv.setText(falgType);
        }
    }

    @OnClick({R.id.bt_change, R.id.bt_start, R.id.tv_stop_task, R.id.tv_work_route})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.bt_change:
                final String[] array = {"搜索车辆", "扫描车牌"};

                BottomSheetDialog dialog = new BottomSheetDialog(WorkTaskListActivity.this,
                        array, new BottomSheetDialog.OnItemClickListener() {

                    @Override
                    public void onItemClick(int position) {
                        switch (position) {
                            case 0:
                                CommonSearchActivity.start(WorkTaskListActivity.this,
                                        CommonSearchActivity.MODE_SEARCH_PLATE, arrangeTask
                                                .getId());
                                break;
                            case 1:
                                ScanCaptureActivity.start(WorkTaskListActivity.this,
                                        ScanCaptureActivity.TYPE_PLATE_NUM,
                                        ScanCaptureActivity.MODE_BIND_CAR, arrangeTask.getId
                                                ());
                                break;
                            default:
                                break;
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.bt_start:
                switch (arrangeTask.getState()) {
                    case WORK_TASK_STATE_NOT_START:
                        //开启任务
                        ApiAcceptArrangeTask();
                        break;
                    case WORK_TASK_STATE_START:
                        //完成任务 还车或完成任务
                        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
                            showSPTFinishWork();
                        } else {
                            showSelectPopupWindow();
                        }
                        break;
                    default:
                        break;
                }
                break;
            case R.id.tv_stop_task:
                if (arrangeTask.getState() == WORK_TASK_STATE_NOT_START) {
                    ToastUtil.showToast("请先开启任务");
                    return;
                }

                if (arrangeTask.getIsSuspended() == 0) {
                    //暂停
                    apiStopTask(arrangeTask.getId());
                } else {
                    //开启
                    apiRestartTask(arrangeTask.getId());
                }
                break;
            case R.id.tv_work_route:
                if (arrangeTask.getState() == WORK_TASK_STATE_NOT_START) {
                    ToastUtil.showToast("请先开启任务");
                    return;
                }
                Intent intent = new Intent(WorkTaskListActivity.this, HxWorkTaskRoutActivity.class);
                intent.putExtra(Constants.IK_ARRANGE_ID, arrangeTask.getId());
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * SPT结束任务
     */
    private void showSPTFinishWork() {
        HxSPTFinishWorkDialog finishWorkDialog = HxSPTFinishWorkDialog.newInstance();
        finishWorkDialog.show(getFragmentManager(), "finish_work");
        finishWorkDialog.setOnUseMoneyClickListener(new HxSPTFinishWorkDialog.OnUseMoneyClickListener() {
            @Override
            public void use(String money) {
                voidFinishTask(money);
            }
        });
    }

    private void voidFinishTask(final String money) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().closeArrangeTask(arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
                            //上传费用
                            apiUploadArrangeTaskCost(money);

                        } else {
                            //关闭弹框
                            if (taskFeeDialog != null && taskFeeDialog.isShowing()) {
                                taskFeeDialog.dismiss();
                                arrangeTask.setState(WORK_TASK_STATE_END);
                                // updateView();
                            } else {
                                if (baseDTO != null) {
                                    ToastUtil.showToast(baseDTO.getMsg());
                                } else {
                                    ToastUtil.showToast("数据异常");
                                }
                            }
                        }
                        setResult();
                        finish();
                    }
                } else {
                    ToastUtil.showToast("数据错误");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });
    }

    private void setResult() {
        Intent intent = new Intent();
        intent.putExtra(Constants.IK_AT_STATE, arrangeTask.getState());
        Log.e("lwjing", "work stata :" + arrangeTask.getState() + " getIsSuspended  " + arrangeTask.getIsSuspended());
        intent.putExtra(Constants.IK_TASK_PAUSE, arrangeTask.getIsSuspended());
        setResult(RESULT_OK, intent);
    }

    private void apiRestartTask(int arrengeTaskId) {
        Call<ArrangeTaskPauseDTO> call = HxTransmitRequestHelper.getRequestApi().getArrangeTaskRestart(arrengeTaskId);
        autoClose(call);

        call.enqueue(new Callback<ArrangeTaskPauseDTO>() {
            @Override
            public void onResponse(Call<ArrangeTaskPauseDTO> call, Response<ArrangeTaskPauseDTO>
                    response) {
                ArrangeTaskPauseDTO arrangeWorkTaskDTO = response.body();
                if (arrangeWorkTaskDTO != null && arrangeWorkTaskDTO.isSuccessful()) {
                    ArrangeTaskPauseDTO.ArrangeTaskPause data = arrangeWorkTaskDTO.getData();
                    if (data != null) {
                        Log.e("lwjing", "重启成功:" + data.toString());
                        ToastUtil.showToast("任务单继续执行");
                        arrangeTask.setIsSuspended(0);
                        tv_stop_task.setImageResource(R.drawable.control_pause);
                    } else {
                        ToastUtil.showToast(arrangeWorkTaskDTO.getMsg());
                    }
                } else {
                    if (arrangeWorkTaskDTO != null) {
                        ToastUtil.showToast(arrangeWorkTaskDTO.getMsg());
                    } else {
                        ToastUtil.showToast("操作失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrangeTaskPauseDTO> call, Throwable t) {
                Log.d(TAG, "onFailure:Data --->" + t);
                ToastUtil.showToast("网络故障");
            }
        });
    }

    private void apiStopTask(int arrengeTaskId) {
        Call<ArrangeTaskPauseDTO> call = HxTransmitRequestHelper.getRequestApi().getArrangeTaskPause(arrengeTaskId);
        autoClose(call);

        call.enqueue(new Callback<ArrangeTaskPauseDTO>() {
            @Override
            public void onResponse(Call<ArrangeTaskPauseDTO> call, Response<ArrangeTaskPauseDTO>
                    response) {
                ArrangeTaskPauseDTO arrangeWorkTaskDTO = response.body();
                if (arrangeWorkTaskDTO != null && arrangeWorkTaskDTO.isSuccessful()) {
                    ArrangeTaskPauseDTO.ArrangeTaskPause data = arrangeWorkTaskDTO.getData();
                    if (data != null) {
                        Log.e("lwjing", "暂停成功:" + data.toString());
                        ToastUtil.showToast("任务单暂停执行");
                        arrangeTask.setIsSuspended(1);
                        tv_stop_task.setImageResource(R.drawable.control_play);
                    } else {
                        ToastUtil.showToast(arrangeWorkTaskDTO.getMsg());
                    }
                } else {
                    if (arrangeWorkTaskDTO != null) {
                        ToastUtil.showToast(arrangeWorkTaskDTO.getMsg());
                    } else {
                        ToastUtil.showToast("操作失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrangeTaskPauseDTO> call, Throwable t) {
                Log.d(TAG, "onFailure:Data --->" + t);
                ToastUtil.showToast("网络故障");
            }
        });
    }

    /**
     * 完成任务popupWindow
     */
    private void showSelectPopupWindow() {

        taskFeeDialog = new TaskFeeDialog(this);
        taskFeeDialog.setItemClickCallBack(new TaskFeeDialog.ItemClickCallBack() {
            @Override
            public void itemClick(int position, String fee) {

                ApiCloseArrangeTask(position, fee);
            }
        });
        taskFeeDialog.show();
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            taskFeeDialog.setEtFeeVisible(true);
        } else {
            taskFeeDialog.setEtFeeVisible(false);
        }
    }


    /*还车接口请求*/
    private void ApiUnbindVehicle() {
        //        final Dialog dialog = DialogUtil.getWaitDialog(this, "请稍等");
        //        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().unbindVehicle(arrangeTask.getPlanVehicle(), null);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                //                dialog.dismiss();
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null) {
                        if (baseDTO.isSuccessful()) {
                            return;
                        } else {
                            ToastUtil.showToast(baseDTO.getMsg());
                        }
                    }
                } else {
                    ToastUtil.showToast("还车失败");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                //                dialog.dismiss();
                ToastUtil.showToast("还车失败");
            }
        });

    }

    /**
     * @desc 厂内巡检
     * @author songxf
     * created at 2017/9/1 17:38
     */
    private void ApiRequestDatafindXunJianStructure(int status, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<HxInHousePollingBean> call = HxTransmitRequestHelper.getRequestApi().getFindXunJianStructure(arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<HxInHousePollingBean>() {
            @Override
            public void onResponse(Call<HxInHousePollingBean> call, Response<HxInHousePollingBean> response) {
                HxInHousePollingBean pollingBean = response.body();
                if (response.isSuccessful() && pollingBean.isSuccessful()) {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_SUCCESS);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                    if (pollingBean.getData().size() == 0 || pollingBean.getData() == null) {
                        updateLoadStatus(LOAD_NO_DATA);
                    }
                    mDataBeanList.clear();
                    mDataBeanList.addAll(pollingBean.getData());
                    mPollingAdpater.notifyDataSetChanged();

                } else {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_ERROR);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                    ToastUtil.showToast("请求接口失败！");
                }
            }

            @Override
            public void onFailure(Call<HxInHousePollingBean> call, Throwable t) {
                if (refreshView == null) {
                    updateLoadStatus(LOAD_ERROR);
                } else {
                    refreshView.onRefreshComplete();
                }
                ToastUtil.showToast("网络故障！");
            }
        });

    }

    // 0 厂站巡检 1其他派工
    private void ApiRequestData(int status, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<WorkTaskListDTO> call = HxTransmitRequestHelper.getRequestApi().getWorkTaskList(arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<WorkTaskListDTO>() {
            @Override
            public void onResponse(Call<WorkTaskListDTO> call, Response<WorkTaskListDTO> response) {

                WorkTaskListDTO workTaskListDTO = response.body();
                if (response.isSuccessful() && workTaskListDTO != null) {
                    if (workTaskListDTO.isSuccessful()) {
                        if (refreshView == null) {
                            updateLoadStatus(LOAD_SUCCESS);
                        } else {
                            refreshView.onRefreshComplete();
                        }

                        workTaskDatas.clear();
                        workTaskDatas.addAll(workTaskListDTO.getWorkTaskInfos());
                        workTaskListAdapter.setNewData(workTaskDatas);
                        //                        workTaskListAdapter.notifyDataSetChanged();
                    } else {
                        if (refreshView == null) {
                            updateLoadStatus(LOAD_ERROR);
                        } else {
                            refreshView.onRefreshComplete();
                        }
                        ToastUtil.showToast(workTaskListDTO.getMsg());
                    }
                } else {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_ERROR);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                    ToastUtil.showToast("请求接口失败！");
                }
            }

            @Override
            public void onFailure(Call<WorkTaskListDTO> call, Throwable t) {
                if (refreshView == null) {
                    updateLoadStatus(LOAD_ERROR);
                } else {
                    refreshView.onRefreshComplete();
                }
                ToastUtil.showToast("网络故障！");
            }
        });
    }


    private void ApiChangCar(final String plateNum) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().addVehicle(plateNum, arrangeTask.getId());
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        arrangeTask.setRealVehicle(plateNum);
                        updateView();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constants.RET_WT_STATE) {
                int workTaskState = data.getIntExtra(Constants.IK_WT_STATE, 0);
                workTaskDatas.get(ret_pos).setWorkTaskState(workTaskState);
                workTaskListAdapter.notifyItemChanged(ret_pos);
            } else if (requestCode == Constants.RET_SWEEP) {
                arrangeTask.setRealVehicle(data.getStringExtra(Constants.IK_PLATE_NUM));
                updateView();
            } else if (requestCode == Constants.RET_SEARCH) {
                arrangeTask.setRealVehicle(data.getStringExtra(Constants.IK_PLATE_NUM));
                updateView();
            } else if (requestCode == Constants.RET_XJ_STATE) {
                int position = data.getIntExtra(Constants.IK_XJ_POSITION, 0);
                int xjState = data.getIntExtra(Constants.IK_XJ_STATE, 0);
                mPollingAdpater.setFinishState(position, xjState);
            }
        }
    }
}